package com.tensquare.friend.interceptors;

import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import util.JwtUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by Administrator on 2021/6/15.
 * 解析token的拦截器,对于某些操作需要进行权限判定.只有token正确并且是admin角色才能操作
 */
@Component
public class JwtInterceptor extends HandlerInterceptorAdapter{
    @Autowired
    private JwtUtil jwtUtil;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("经过拦截器");
        String header = request.getHeader("Authorization");
        //判断请求头是否有数据,是不是姨约定Bearer开头
        if (StringUtils.isNotBlank(header) && header.startsWith("Bearer ")) {
            String token = header.substring(7);
            Claims claims = jwtUtil.parseToken(token);
            if (claims != null) {
                String role = (String) claims.get("role");
                if ("admin".equals(role) ) {
                   //如果是管理员
                    request.setAttribute("admin_claims",claims);
                }
                if ("user".equals(role)){
                    //如果为普通用户
                    request.setAttribute("user_claims",claims);
                }
            }
        }
        return true;
    }
}
